package org.gurms.common.validate;

import java.lang.reflect.Method;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.gurms.common.exception.GurmsServiceException;
import org.gurms.common.util.SpringUtil;

public class GurmsValidInterceptor implements MethodInterceptor {

	/**
	 * 拦截器，主要用来根据配置自动效验dto
	 */
	public Object invoke(MethodInvocation invocation) throws Throwable {
		// TODO Auto-generated method stub
		Method method = invocation.getMethod();
		if(method.isAnnotationPresent(GurmsValid.class)){
			GurmsValid valid = method.getAnnotation(GurmsValid.class);
			
			String clzName = valid.type().getName();
			String[] props = valid.props();

			Object[] args = invocation.getArguments();
			Validation gv = SpringUtil.getBean("gurmsValidator");
			String validMsg = "";
			for(Object arg : args){
				if(valid.type().isInstance(arg)){
//					String script = gv.script(clzName, props);
//					System.out.println(script);
					validMsg = gv.valid(clzName, props, arg);
					System.out.println(validMsg);
					break;
				}
			}
			
			if(validMsg.length() > 0){
				throw new GurmsServiceException(validMsg);
			}
		}
		
		return invocation.proceed();
	}

}
